<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  <meta http-equiv="Content-Style-Type" content="text/css">
  <title>Prolog interpreter in Java: Jinni - User Guide</title>
  <meta name="Description" content="innovative software development specializing in Java and Prolog based Internet programming and Intelligent Mobile Agent building tools">
  <meta name="Generator" content="Cocoa HTML Writer">
  <meta name="CocoaVersion" content="1138">
  <style type="text/css">
    p.p4 {margin: 0.0px 0.0px 0.0px 0.0px; font: 12.0px Times}
    p.p6 {margin: 0.0px 0.0px 12.0px 0.0px; font: 12.0px Times; color: #3333ff}
    p.p7 {margin: 0.0px 0.0px 0.0px 0.0px; font: 12.0px Times; min-height: 14.0px}
    p.p8 {margin: 0.0px 0.0px 0.0px 0.0px; font: 14.0px Times}
    p.p9 {margin: 0.0px 0.0px 12.0px 0.0px; font: 12.0px Times}
    p.p13 {margin: 0.0px 0.0px 12.0px 0.0px; font: 12.0px Times; color: #3366ff}
    p.p14 {margin: 0.0px 0.0px 0.0px 0.0px; font: 10.0px Courier}
    p.p15 {margin: 0.0px 0.0px 0.0px 0.0px; font: 10.0px Times}
    p.p16 {margin: 0.0px 0.0px 12.0px 0.0px; font: 10.0px Times}
    p.p17 {margin: 0.0px 0.0px 0.0px 0.0px; font: 10.0px Courier; min-height: 12.0px}
    p.p18 {margin: 0.0px 0.0px 12.0px 0.0px; font: 10.0px Courier}
    li.li4 {margin: 0.0px 0.0px 0.0px 0.0px; font: 12.0px Times}
    span.s1 {text-decoration: underline ; color: #0000ee}
    span.s2 {color: #000000}
    span.s3 {font: 12.0px Courier}
    span.s4 {font: 12.0px Times}
    table.t1 {width: 548.0px}
    td.td1 {width: 245.0px; margin: 0.5px 0.5px 0.5px 0.5px; padding: 1.0px 1.0px 1.0px 1.0px}
    td.td2 {width: 293.0px; margin: 0.5px 0.5px 0.5px 0.5px; padding: 1.0px 1.0px 1.0px 1.0px}
    td.td3 {width: 215.0px; margin: 0.5px 0.5px 0.5px 0.5px; padding: 1.0px 1.0px 1.0px 1.0px}
    td.td4 {width: 323.0px; margin: 0.5px 0.5px 0.5px 0.5px; padding: 1.0px 1.0px 1.0px 1.0px}
    ul.ul1 {list-style-type: disc}
  </style>
</head>
<body>
<h1 style="margin: 0.0px 0.0px 16.0px 0.0px; text-align: center; font: 24.0px Times"><b>Kernel Prolog: a Lightweight Prolog-in-Java Interpreter with <i>Fluent</i> based Built-ins</b></h1>
<h1 style="margin: 0.0px 0.0px 16.0px 0.0px; text-align: center; font: 24.0px Times"><b>USER GUIDE</b></h1>
<h3 style="margin: 0.0px 0.0px 14.0px 0.0px; text-align: center; font: 14.0px Times"><b>Paul Tarau, November 1999</b></h3>
<h2 style="margin: 0.0px 0.0px 14.0px 0.0px; font: 18.0px Times"><b>About Kernel Prolog</b></h2>
<p class="p4"><i>Kernel Prolog</i> supports a simplified CUT-less and operatorless subset of ISO Prolog. Its main merit is a redesigned set of built-ins and an axiomatic reconstruction of Prolog on top of Horn Clauses with first class Fluents. Kernel Prolog Solvers (first class LD-resolution interpreters), together with Sources and Sinks provide stateful objects needed to represent the state of the Solvers as well as for interoperation with the embedding Object Oriented environment.</p>
<h2 style="margin: 0.0px 0.0px 14.0px 0.0px; font: 18.0px Times"><b>Getting started</b></h2>
<h3 style="margin: 0.0px 0.0px 14.0px 0.0px; font: 14.0px Times"><b>Installation and essential files</b></h3>
<p class="p4">Make sure you uncompress the provided *.zip or *.tar.gz file containing Kernel Prolog. The toplevel interaction starts with something like</p>
<p class="p6">java -cp bin JinniMain</p>
<p class="p4">The core of Kernel Prolog is in the Java classes inside the subdirectory <a href="file:///Users/tarau/Library/Containers/com.apple.TextEdit/Data/Desktop/go/code/nprolog/doc/tarau/jinni/"><span class="s1"><b>tarau/jinni</b></span></a>. Look at the Kernel Prolog <a href="file:///Users/tarau/Library/Containers/com.apple.TextEdit/Data/Desktop/go/code/nprolog/doc/docs/index.html"><span class="s1">class documentation</span></a> in directory <a href="file:///Users/tarau/Library/Containers/com.apple.TextEdit/Data/Desktop/go/code/nprolog/doc/docs"><span class="s1">docs</span></a>. The most important file, allowing you to configure/fix problems with Kernel Prolog is <i>lib.pro</i> - containing the definition of most built-ins implemented in Prolog. If you have the Kernel Prolog sources, the essential files to look at are <i>Init.java,Prog.java, IO.java</i> and <i>Builtins.java</i> in directory tarau/jinni and the <i>UserBuiltins.java</i> file showing how to extend Kernel Prolog with new Java operations in the main Jini directory.<span class="Apple-converted-space"> </span></p>
<p class="p7"><br></p>
<p class="p8"><b>Using Kernel Prolog in command line mode:</b></p>
<p class="p9"><br>
<b>Entering a query:</b></p>
<p class="p9">At the prompt "?-" type in a one line Prolog query, as usual, for instance, something like:</p>
<p class="p9"><b><i>?- write(hello),nl.</i></b></p>
<h4 style="margin: 0.0px 0.0px 15.0px 0.0px; font: 12.0px Times"><b>Consulting a new program:</b></h4>
<p class="p4"><b><i>?-[&lt;myprog&gt;].</i></b></p>
<p class="p9"><i>will read in memory the file </i><b><i>&lt;myprog&gt;.pro</i></b><i> program </i>replacing<i> similarly named predicates with new ones. It is actually a shorthand for </i><b><i>reconsult/1</i></b><i>. To </i>accumulate<i> clause for similarly named predicates, use </i><b><i>consult/1</i></b><i>.</i></p>
<p class="p9"><b><i>?-co.</i></b></p>
<p class="p9"><i>will reconsult </i>again<i> the the last consulted file. If you start Kernel Prolog with its visual environment, try something like:</i></p>
<p class="p9"><b><i>?-ide.</i></b></p>
<p class="p9"><i>to lauch an instance of the IDE, or</i></p>
<p class="p9"><b><i>?-[vq8],go.</i></b></p>
<p class="p9"><i>to run a visual N-Queens program.</i> <br>
 </p>
<h3 style="margin: 0.0px 0.0px 14.0px 0.0px; font: 14.0px Times"><b>Using Kernel Prolog through an applet</b></h3>
<p class="p4">Type <b>appletviewer JinniGUI.htm</b>l . Enter, for instance, in the query window:</p>
<p class="p9"><b>append(Xs,Ys,[1,2,3]).</b></p>
<p class="p9">You will see the applet displaying the results. Applets can load files <i>located at the site where they originate from</i>. Try</p>
<p class="p9"><b>?-[q8],queens(8,X)</b></p>
<p class="p9">to consult over the net and run the N-queens program. <i>To launch an instance of a simple IDE with embedded editor and query processor, type</i></p>
<p class="p9"><b><i>?-ide.</i></b> <br>
 </p>
<h3 style="margin: 0.0px 0.0px 14.0px 0.0px; font: 14.0px Times"><b>Building simple Prolog programs with Kernel Prolog</b></h3>
<p class="p4">With the editor of your choice create a text file called simple.pro, with the following content:</p>
<p class="p6">c(X):-a(X),b(X).</p>
<p class="p6">a(1).<span class="s2"> <br>
</span>a(2).<span class="s2"> <br>
</span>a(3).</p>
<p class="p6">b(2).<span class="s2"> <br>
</span>b(3).<span class="s2"> <br>
</span>b(4).</p>
<p class="p9">In a shell window (DOS command, csh, bash etc.), type <b>java JinniMain</b> to launch the standalone command line Jinni interpreter, prompting you with "?- " to enter commands/queries. To load the file type:</p>
<p class="p6"><span class="s2">?-</span>[simple].</p>
<p class="p9">then try the query:</p>
<p class="p6"><span class="s2">?-</span>c(X).</p>
<p class="p9"><b>Example of reading/writing to files:</b></p>
<p class="p9">Kernel Prolog can read files or URLs and write files in command line mode. In applet mode Kernel Prolog can only read files described as URLs, from from the directory it comes from. Try:</p>
<p class="p6"><span class="s2">?-</span>clause_file_writer('example.txt',File),fprint_clause(File,example(one)),stop(File).</p>
<p class="p9">followed by:</p>
<p class="p6"><span class="s2">?-</span>file_clause_reader('example.txt',File),fread(File,X),stop(File),println(X).</p>
<p class="p9">Jinni can open a URL over the net, in a way similar to file. Try:</p>
<p class="p6"><span class="s2">?-</span>file_char_reader('http://www.binnetcorp.com',Reader),source_list(Reader,Chars),put_codes(Chars),fail.</p>
<p class="p9">to print out a HTML file fetched directly from the Web. <br>
 </p>
<h1 style="margin: 0.0px 0.0px 16.0px 0.0px; font: 24.0px Times"><b>LANGUAGE DEFINITION</b></h1>
<h3 style="margin: 0.0px 0.0px 14.0px 0.0px; font: 14.0px Times"><b>Syntax</b></h3>
<p class="p4">Unicode based language internationlization is supported by using only the (wide) <b>char</b> type and appropriate JDK 1.x reader and writer classes.<span class="Apple-converted-space"> </span></p>
<p class="p4">Kernel Prolog's parser and tokenizer are very small and based on Java's own built-in parsing/tokenizing libraries (StreamTokenizer). This allows relying on code already in  browsers instead of having to load classes over the network. In the future, as Kernel Prolog is heading towards plain Natural Language input through speech recognition software, it's internal syntax (which might already look too restrictive to Prolog programmers) will be generated through a preprocessor supporting user defined distfix operators. As such, kernel Prolog is expected to be able to emulate full Prolog syntax and more. However, Kernel Prolog's current syntax is <i>restricted to standard prefix Prolog terms</i> of the form f(T1,..Tn), with the infix operators ':-' and ',' accepted <i>only </i>at top level:</p>
<p class="p9">Clause ::                                 Head :- Body. <br>
Clause ::                                 Head. <br>
Head ::                                   Term <br>
Body ::                                   CommaSeparatedTerms <br>
CommaSeparatedTerms ::     Term {,Term}* <br>
Term ::                                   Const | VARIABLES | CompoundTerm <br>
CompoundTerm ::                  IDENTIFIER(CommaSeperatedTerms) <br>
Const ::                                  IDENTIFIER  |  INTEGER  |  REAL</p>
<p class="p9">IDENTIFIERs starting with lower case characters and containing <i>only</i> alphabetical characters do not require quoting, for instance <b>is(X,99)</b> is a valid term. When IDENTIFIERs start with upper case or contain non-alphabetical characters they require single quotes, i.e. you should write something like <b>':-'(a(X),b(X))</b> or <b>'+'(3,4)</b>. Variables start with upper case characters or "_". Both % one line and /* ... */ multiple line comments are supported. A way to run under full Prolog programs with trickier operator syntax is to <i>write them to a file using plain term syntax</i>.</p>
<p class="p9">While this syntax looks restrictive, in fact, it is enough for expressing everything Prolog semantics actually supports. The following table shows how to handle the differences: <br>
  <br>
 </p>
<table width="548.0" cellspacing="0" cellpadding="0" class="t1">
  <tbody>
    <tr>
      <td valign="middle" class="td1">
        <p class="p4">Prolog:</p>
      </td>
      <td valign="middle" class="td2">
        <p class="p4">Jinni:</p>
      </td>
    </tr>
    <tr>
      <td valign="middle" class="td1">
        <p class="p4">assert((b(X):-a(X),c(X)) </p>
      </td>
      <td valign="middle" class="td2">
        <p class="p4">assert(':-'(a(X),','(b(X),c(X))))</p>
      </td>
    </tr>
    <tr>
      <td valign="middle" class="td1">
        <p class="p4">X is 3+4</p>
      </td>
      <td valign="middle" class="td2">
        <p class="p4">is(X,'+'(3,4))</p>
      </td>
    </tr>
  </tbody>
</table>
<p class="p9">Some simple definitions like eq(X,X), and if/3 present in Jinni, allow alternative writings like: <br>
 </p>
<table width="548.0" cellspacing="0" cellpadding="0" class="t1">
  <tbody>
    <tr>
      <td valign="middle" class="td3">
        <p class="p4">Prolog:</p>
      </td>
      <td valign="middle" class="td4">
        <p class="p4">Jinni:</p>
      </td>
    </tr>
    <tr>
      <td valign="middle" class="td3">
        <p class="p4">(X=1-&gt;Y=2;Y=3)</p>
      </td>
      <td valign="middle" class="td4">
        <p class="p4">if(eq(X,1),eq(Y,2),eq(Y,3))</p>
      </td>
    </tr>
    <tr>
      <td valign="middle" class="td3">
        <p class="p4">(X=1-&gt;true;X=2)</p>
      </td>
      <td valign="middle" class="td4">
        <p class="p4">if(eq(X,1),true,eq(X,2))</p>
      </td>
    </tr>
  </tbody>
</table>
<h2 style="margin: 0.0px 0.0px 14.0px 0.0px; font: 18.0px Times"><b>Semantics</b></h2>
<p class="p4">Kernel Prolog can be seen as a collection of Horn Clause Interpreters running LD-resolution on a default clause database and calling built-in operations. Through built-in calls, they possess the ability to create other query first class engines and interoperate with Java through a set of stateful objects called <b><i>Fluents</i></b>.</p>
<p class="p9">Fluents are created with specific constructors, usually named the name of the type, by converting from other fluents or conventional Prolog data structures like Terms, Lists or Databases. All Fluents are enabled with a <b>stop/1</b>  operation which releases their resources (most Fluents also call stop/1 on backtracking to free resources).</p>
<p class="p9"><b><i>Sources</i></b> are Fluents enabled with an extra <b>get/2</b> operation. Typical Sources are Horn Clause Engines, File, URL or String Readers, Fluents built form Prolog lists. <b><i>Sinks</i></b> are fluents enabled with an extra <b>put/2 and collect/2 </b>operation<b>. </b>Typical fluents are ClauseWriters or CharWriters targeted to Files,  TermCollectors  (implemented as a Java Vectors collecting Prolog terms), StringSinks (implemented as a Java StringBuffers colecting String representations of Prolog terms). Prolog Databases are first class citizens implemented as extensions of Sources which provide <b>add/2, remove/2, collect/2</b> operations.</p>
<p class="p9">Fluents are<i> resources</i> which go throuh state transitions as a result of  <b>put/2</b> or <b>get/2 </b>operations. They end their life cycle in a stopped state when all the resources they hold are freed. An algebra of Fluent composers provides abstract operations on fluents. For instance, <b>append_sources/3</b> creates a new Source with a <b>get/2</b> operation such that when the first Source is stopped, iteration continues over the elements of the second source.   <b>Compose_sources/3</b> provides a cartesian product style composition, the new<b> get/2</b> operation returning pairs of elements of the first and second Source. <b>Split_source/3</b> creates 2 Source objects identical to the Source given as first argument. It allows writing programs which iterate over a given Source multiple times. Sources and Sinks are related through a <b>discharge(Source,Sink) </b>operation which sends all the elements of the Source to the given Sink. <br>
 </p>
<h4 style="margin: 0.0px 0.0px 15.0px 0.0px; font: 12.0px Times"><b>Programming without CUT</b></h4>
<p class="p4">Kernel Prolog does not implement Prolog's CUT. With embedded <b>if/3</b> constructs, <b>not/1</b> and using distinct patterns returned as results from built-ins, to allow<span class="Apple-converted-space"> </span></p>
<p class="p4">distinct first argument based case analysis, someone can cover easily most uses of CUT. Using <b>once(Goal) </b>allows restricting your attention to the first solution of Goal, in a way similar to <b>Goal,! </b>in Prolog.</p>
<h1 style="margin: 0.0px 0.0px 16.0px 0.0px; text-align: center; font: 24.0px Times"><b>Some Classic Kernel Prolog built-in predicates</b></h1>
<p class="p4">Kernel Prolog's built-in predicates follow the spirit of Prolog while simplifying when possible and adjusting to its restricted syntax. For their complete executable specification and typical use cases we refer to the file tarau/jinni/lib.pro containing the Kernel Prolog system library.</p>
<h3 style="margin: 0.0px 0.0px 14.0px 0.0px; font: 14.0px Times"><b>Basic Prolog built-ins:</b></h3>
<ul class="ul1">
  <li class="li4"><b>eq(X,Y): </b>succeeds if X and Y can be unified (as with Prolog's X=Y).</li>
  <li class="li4"><b>write(Arg):</b> writes out a term</li>
  <li class="li4"><b>nl:</b> writes out a new line</li>
  <li class="li4"><b>println(Term): </b>prints out a term on a line - synchronized for multi-threaded use</li>
  <li class="li4"><b>halt: </b>stops Jinni (works in command line mode, but not in applet mode)</li>
  <li class="li4"><b>if(Cond,Then,Else):</b> If <b>Cond </b>succeeds, executes <b>Then</b> with possible bindings provided by <b>Cond</b>. If <b>Cond</b> fails, the bindings it produces are undone and <b>Else</b> is executed.</li>
  <li class="li4"><b>if_any(Cond,Then,Else):</b> For each alternative <b>Cond </b>thatsucceeds, executes <b>Then</b> with  bindings provided by <b>Cond</b>. If <b>Cond</b> fails, the bindings it produces are undone and <b>Else</b> is executed.</li>
  <li class="li4"><b>not(Goal):</b> succeeds if <b>Goal</b> fails but produces no bindings. Fails if Goal succeeds.</li>
  <li class="li4"><b>and(A,B):</b> executes <b>A</b> and if this succeeds, <b>B</b></li>
  <li class="li4"><b>or(A,B):</b> executes A and, after backtracking from A, executes B</li>
  <li class="li4"><b>repeat:</b> repeatedly executes the goal following it, until it succeeds</li>
  <li class="li4"><b>listing/0, listing/1:</b> lists the predicates in the default database</li>
  <li class="li4"><b>put_codes(IntegerList):</b> writes out a list of character codes as a String</li>
  <li class="li4"><b>read(X):</b> reads in a term <b>X</b>. In applet mode this usually happens from a second editable input field, not the one usually goals are read in.</li>
  <li class="li4"><b>read_clause(Clause,Vars,ClauseWithNamedVars,NamedVars)</b>: reads in a clause together with its variables in a term '[]'(V1,...Vn) and a copy of the clause and a copy of its variables instantiated to their original names</li>
  <li class="li4"><b>var(T):</b> succeeds if <b>T </b>is currently a free variable</li>
  <li class="li4"><b>nonvar(T):</b> succeeds if T is currently bound to a non-variable term</li>
  <li class="li4"><b>integer(T):</b> succeeds if T is instantiated currently to an integer</li>
  <li class="li4"><b>float(T):</b> succeeds if T is instantiated currently to an float value</li>
  <li class="li4"><b>compound(T):</b> succeeds if T is instantiated currently to a compound term</li>
  <li class="li4"><b>atomic(T):</b> succeeds if T is instantiated currently to an integer, float or constant object</li>
  <li class="li4"><b>numeric(T): </b>succeeds if T is instantiated currently to an integer of float value</li>
  <li class="li4"><b>arg(Nth,Term,Arg):</b> returns the Nth argument of a compound term <b>Term</b>, in particular its functor for <b>Nth</b>=0.</li>
  <li class="li4"><b>functor(F,N,T):</b> <b>T </b>is a new term <b>T</b> based on functor <b>F</b> of arity <b>N</b>, i.e. F(V1,...,Vn) with <b>V1,...,Vn</b> fresh variables.</li>
  <li class="li4"><b>univ(T,FXs) or '=..'(T,FXs) </b>convert between a term <b>f(X1,...,Xn)</b> and its "universal"  list representation <b>[f,X1,...,Xn]</b>.</li>
  <li class="li4"><b>compute(Operation,Operand1,Operand2,Result):</b> raw arithmetic processor. Used as in: <b>compute('+',2,3,R)</b> with <b>R=5</b> or as in in <b>compute('?',1,2,R)</b>,with <b>R=-1</b> (with <b>R</b>=0 if <b>Operand1==Operand2 </b>and <b>R=1</b> if <b>Operand1&gt;Operand2</b>).</li>
  <li class="li4"><b>is(Value,Expression): </b>like Prolog's is/2, evaluates its second argument and unifies the result with the first, for example <b>is(R,'+'(1,'*'(2,3)))</b> will bind <b>R</b> to <b>7</b>.</li>
  <li class="li4"><b>append(Xs,Ys,Zs):</b> succeeds when lists <b>Xs</b> and <b>Ys</b> concatenate to <b>Zs</b>. Can be used with  various patterns, e.g. with known <b>Zs</b> and unknown <b>Xs</b>, <b>Ys</b>.</li>
  <li class="li4"><b>member(X,Xs):</b> enumerates through backtracking each <b>X </b>such as <b>X</b> is a member of the list <b>Xs</b></li>
  <li class="li4"><b>for(I,Min,Max): </b>enumerates through backtracking each <b>I</b> from <b>Min</b> to <b>Max</b></li>
  <li class="li4"><b>reconsult('&lt;FILE&gt;.pro'):</b> reconsults a file, i.e. <i>reads</i> and <i>asserts</i> each clause in the file to the database while <i>overriding</i> predicate definitions in the database with <i>new</i> definitions read from the file. To avoid confusion with Perl, the suffix .pro for Jinni programs is strongly encouraged. The shorthand [&lt;FILE&gt;] results in having the sufix .pro appended to &lt;FILE&gt; and then in a call to <b>reconsult('&lt;FILE&gt;.pro')</b>.</li>
  <li class="li4"><b>consult('&lt;FILE&gt;.pro'):</b> consults a file, i.e. reads and asserts each clause in the file to the database <i>without destroying</i> other clauses of the same predicate. This can lead to <i>unwanted multiple occurrences of clauses</i>, use <b>reconsult/1</b> instead, whenever possible</li>
  <li class="li4"><b>co:</b> shorthand for redoing the last <b>reconsult </b>operation</li>
  <li class="li4"><b>assert(':-'(Head,Body)) or assert(Head): </b>puts a new clause on the (remote or local) blackboard, using an <b>out/1</b> operation. If absent, <b>Body</b> defaults to <b>true</b></li>
  <li class="li4"><b>retract1(Head): </b>remove a matching clause from the (remote or local) blackboard, using <b>cin/1</b></li>
  <li class="li4"><b>clause(Head,Body):</b> backtracks over the clause currently matching <b>':-'(Head,Body)</b> on the (remote or local) blackboard</li>
  <li class="li4"><b>retract(Head):</b> backtracks over the clauses currently matching <b>':-'(Head,Body)</b> on the (remote or local) blackboard and tries to applies <b>retract1(Head)</b> to each. Better to be avoided if multiple threads work in parallel, use <b>retract1/1</b> instead</li>
  <li class="li4"><b>findall(Pattern,Goal,Answers): builds the list Answers by collecting copies of all answers of Goal of the form Pattern</b></li>
  <li class="li4"><b>length/2: </b>measures the length of a list or generates a new list of give length</li>
  <li class="li4"><b>compare/3:</b> (restricted to arithmetic terms) compares with operation &lt;,=,&gt; provided as first argument its second and third arguments</li>
  <li class="li4"><b>forall(Cases,Goal)</b>: runs Goal for all solutions provided by Cases, through double negation</li>
  <li class="li4"><b>trace/0</b> and <b>notrace/0</b> turn on/off tracing</li>
  <li class="li4"><b>why(Goal)</b>: runs Goal and prints out instantiated steps of  its execution</li>
  <li class="li4"><b>sleep(Seconds):</b> sleeps without using CPU for a given number of seconds</li>
  <li class="li4"><b>sleep_ms(Miliseconds)</b>: sleeps without using CPU for a given number of miliseconds</li>
</ul>
<p class="p4"><b><i>Definitions of these and other built-ins are </i></b><i>provided in file </i><a href="file:///Users/tarau/Library/Containers/com.apple.TextEdit/Data/Desktop/go/code/nprolog/doc/tarau/jinni/lib.pro"><span class="s1"><i>lib.pro.</i></span></a></p>
<h3 style="margin: 0.0px 0.0px 14.0px 0.0px; font: 14.0px Times"><b>Operations on Interpreters (instances of Source Operations)</b></h3>
<ul class="ul1">
  <li class="li4"><b>answer_source(AnswerPattern,Goal,Interpreter):</b> creates and returns a new interpreter (a <b>Source</b>)</li>
  <li class="li4"><b>get(Interpreter,Answer):</b> asks an engine given as a <b>Interpreter</b> for a new <b>Answer, </b>which will be of the form <b>the(AnswerPatternInstance)</b> on success and which will be <b>no</b> on failure as well on any call after failure occurred</li>
  <li class="li4"><b>stop(Interpreter):</b> makes sure the engine is stopped. Only <b>no</b> answers will be available from the engine in the future.</li>
</ul>
<h3 style="margin: 0.0px 0.0px 14.0px 0.0px; font: 14.0px Times"><b>File, socket, URL and string based stream operations (based on Source operations)</b></h3>
<p class="p4">Jinni extends ISO Prolog's stream I/O based operations to URLs and strings - to give a uniform view of all of them as streams.</p>
<h4 style="margin: 0.0px 0.0px 15.0px 0.0px; font: 12.0px Times"><b>Output operations:</b></h4>
<ul class="ul1">
  <li class="li4"><b>clause_file_writer(FileName</b>,<b>ClauseWriter)</b> opens a file in Prolog Clause or Term (structured data) write mode</li>
  <li class="li4"><b>char_file_writer(FileName,Writer)</b> opens a file in character code write mode</li>
  <li class="li4"><b>stop(Writer):</b> closes a Writer</li>
  <li class="li4"><b>get_stdout(ClauseWriter):</b> returns the standard output stream (as a ClauseWriter Sink)</li>
  <li class="li4"><b>fprint_clause(ClauseWriter,Name):</b> "pretty prints" a term followed by a dot and a newline to a ClauseWriter</li>
  <li class="li4"><b>fwrite(ClauseWriter,Term):</b> prints a term to a stream</li>
  <li class="li4"><b>fprint_codes(ClauseWriter,IntegerList):</b> writes out a character code list</li>
  <li class="li4"><b>fprintln(ClauseWriter,Term):</b>  writes out a term</li>
  <li class="li4"><b>fnl(ClauseWriter): </b>writes out a new line character</li>
  <li class="li4"><b>term_string_collector(StringSink):</b> opens a string stream based on a Java StringBuffer to which terms, lines, characters can be written</li>
  <li class="li4"><b>term_collector(TermCollector):</b> opens a Vector to which terms, lines, characters can be accumulated</li>
  <li class="li4"><b>collect(Sink,String):</b> collects the content of a sink to an appropriat Prolog object</li>
</ul>
<h4 style="margin: 0.0px 0.0px 15.0px 0.0px; font: 12.0px Times"><b>Input operations:</b></h4>
<ul class="ul1">
  <li class="li4"><b>file_char_reader(FileorURLName,ClauseReader)</b>: opens a file or URL for reading character codes</li>
  <li class="li4"><b>file_clause_reader(FileorURLName,ClauseReader)</b>: opens a file or URL for reading character terms and clauses (structured data)</li>
  <li class="li4"><b>stop(ClauseReader):</b> closes a <b>ClauseReader</b></li>
  <li class="li4"><b>get(ClauseReader,ClauseWithInfo): </b>reads  a Clause with related info (Variables, Variable Names etc.)</li>
  <li class="li4"><b>get_stdin(ClauseReader):</b> returns the standard input stream</li>
  <li class="li4"><b>fread(ClauseReader,Clause):</b> reads a Clause from a ClauseReader</li>
  <li class="li4"><b>fread(ClauseReader,Clause,Vars,ClauseWithNamedVars,VarNames): </b>reads a clause as well as the variables and their names in two terms of the form <b>answer(V1,...Vk)</b> and <b>answer(N1,...,Nk)</b></li>
  <li class="li4"><b>similar read/N operations are provided with the first argument replaced with (implicit) standard input</b></li>
  <li class="li4"></li>
  <li class="li4"> </li>
</ul>
<h3 style="margin: 0.0px 0.0px 14.0px 0.0px; font: 14.0px Times"><b>Database operations</b></h3>
<ul class="ul1">
  <li class="li4"><b>assert(Clause):</b> puts Clause to the Database</li>
  <li class="li4"><b>retract1(Clause): removes and returns the first matching clause</b></li>
  <li class="li4"><b>all(X,Xs):</b> returns the list <b>Xs </b>of terms currently on the blackboard  matching <b>X </b>(unfiable with X)</li>
  <li class="li4"><b>cin(X,R):</b> removes and returns a term <b>R</b> currently on the blackboard  matching <b>X</b> and fails if no such term exists.</li>
  <li class="li4"><b>rd(X)</b>: tests if a matching term unifiable with X is on the blackboard,  and fails otherwise</li>
</ul>
<h2 style="margin: 0.0px 0.0px 14.0px 0.0px; text-align: center; font: 18.0px Times; min-height: 23.0px"><b></b><br></h2>
<h1 style="margin: 0.0px 0.0px 16.0px 0.0px; text-align: center; font: 24.0px Times"><b>Fluent Based Built-ins and Derived Operations</b></h1>
<h3 style="margin: 0.0px 0.0px 14.0px 0.0px; font: 14.0px Times"><b>Fluent Constructors</b></h3>
<p class="p4">Fluents are created with specific constructors, usually by converting from other Fluents or conventional Prolog data structures like Terms, Lists or Databases. 2. All Fluents are enabled with a stop/1 operation which releases their resources (most Fluents also call stop/1 on backtracking, through their internal undo operation).</p>
<p class="p9">In our Java based reference implementation, the Fluent class looks as follows:</p>
<p class="p6">class Fluent extends SystemObject {<span class="s2"> <br>
</span>  Fluent(Prog p) {<span class="s2"> <br>
</span>    trailMe(p);<span class="s2"> <br>
</span>  }</p>
<p class="p6">  // add the fluent to the parent Interpreter's Trail<span class="s2"> <br>
</span>  protected void trailMe(Prog p) {<span class="s2"> <br>
</span>    if(null!=p) p.getTrail().push(this);<span class="s2"> <br>
</span>  }</p>
<p class="p6">  // usable (through overriding) to release resources<span class="s2"> <br>
</span>  // and/or stop ongoing computations<span class="s2"> <br>
</span>  public void stop() {<span class="s2"> <br>
</span>  }</p>
<p class="p6">  // release resources on backtracking, if needed<span class="s2"> <br>
</span>  protected void undo() {<span class="s2"> <br>
</span>    stop();<span class="s2"> <br>
</span>  }<span class="s2"> <br>
</span>}</p>
<p class="p9">Sources are Fluents enabled with an extra <b>get/2 </b>operation. Typical Sources are Horn Clause Interpreters, File, URL or String Readers, Fluents built form Prolog lists, Fluents iterating over data structures like Vectors or Hashtables or Queues in the underlying implementation language.</p>
<p class="p9">Note that the constructor <b>Fluent(Prog p)</b> does a trailing operation on the caller program p's Trail, and provides and undo operation to be called by <b>p</b> on backtracking, to release resources through the Fluent's stop method.</p>
<p class="p9">In our Java based reference implementation the Source abstract class looks as follows:</p>
<p class="p6">abstract class Source extends Fluent {<span class="s2"> <br>
</span>  Source(Prog p) {<span class="s2"> <br>
</span>    super(p);<span class="s2"> <br>
</span>  }</p>
<p class="p6">  abstract public Term get();<span class="s2"> <br>
</span>}</p>
<p class="p9"><b>Sinks</b> are fluents enabled with an extra <b>put/2</b> and <b>collect/2</b> operation. Typical Sinks are ClauseWriters or CharWriters targeted to TermCollectors (implemented as a Java Vectors collecting Prolog terms), StringSinks (implemented as a Java StringBuffers collecting String representations of Prolog terms), Files.</p>
<p class="p9">In our Java based reference implementation the Sink abstract class looks as follows:</p>
<p class="p13">abstract class Sink extends Fluent {</p>
<p class="p13">  Sink(Prog p) {<span class="s2"> <br>
</span>    super(p);<span class="s2"> <br>
</span>  }</p>
<p class="p13">  // sends T to the Sink for tasks as<span class="s2"> <br>
</span>  // accumulation or printing<span class="s2"> <br>
</span>  abstract public int put(Term T);</p>
<p class="p13">  // return data previously sent to the Sink<span class="s2"> <br>
</span>  // (if collection ability is present)<span class="s2"> <br>
</span>  public Term collect() {<span class="s2"> <br>
</span>    return null;<span class="s2"> <br>
</span>  }<span class="s2"> <br>
</span>}</p>
<p class="p9">Not surprisingly, even Prolog databases are first class citizens implemented as extensions of Sources which provide <b>add/2</b>, <b>remove/2</b>, <b>collect/2</b> operations.</p>
<p class="p9">Fluents can be seen as resources which go through state transitions as a result of<b> put/2</b>, <b>get/2</b> and <b>stop/</b>1 operations. They end their life cycle in a stopped state when all the data structures and/or threads they hold are freed. <br>
 </p>
<h3 style="margin: 0.0px 0.0px 14.0px 0.0px; font: 14.0px Times"><b>Fluent Composers</b></h3>
<p class="p4">Fluent composers provide abstract operations on Fluents. They are usually implemented with lazy semantics.</p>
<p class="p9">For instance,<b> append_sources/3</b> creates a new Source with a get/2 operation such that when the first Source is stopped, iteration continues over the elements of the second Source.</p>
<p class="p9"><b>Compose_sources/3</b> provides a cartesian product style composition, the new <b>get/2</b> operation returning pairs of elements of the first and second Source. <b>Reverse_source/2</b> builds a new Source such that its <b>get/2</b> method returns its elements in reverse order.</p>
<p class="p9"><b>Split_source/3</b> creates two Source objects identical to the Source given as first argument. It allows writing programs which iterate over a given Source multiple times. Sources and Sinks are related through a discharge(Source,Sink) operation which sends all the elements of the Source to the given Sink.</p>
<h3 style="margin: 0.0px 0.0px 14.0px 0.0px; font: 14.0px Times"><b>Fluent Modifiers</b></h3>
<p class="p4">Fluent modifiers allow dynamically changing some attributes of a give Fluent. For instance <b>set_persistent(Fluent,YesNo)</b> is used to make a Fluent survive failure, by disabling its <b>undo</b> method, which, by default, applies the Fluent's <b>stop</b> method on backtracking.</p>
<h3 style="margin: 0.0px 0.0px 14.0px 0.0px; font: 14.0px Times"><b>Interpreters as Answer Sources</b></h3>
<p class="p4">Let us put to work in a more specific way the view of <i>Interpreters as Fluents</i>. All we have to do, is provide is a Fluent constructor, creating an <i>Answer Source</i> from an Answer Pattern and a Goal given to an Interpreter. As a result, we will cover negation, limited pruning through <b>once/1</b>, <b>if-then-else/3</b>, <b>findall/3</b>, <b>var/1</b>, and, beyond standard Prolog, forms of lazy, on-demand generation of sets of solutions, as well as a uniform set of built-ins for manipulation of first class Prolog databases and external objects like Files or URLs.</p>
<p class="p9"><b>Answer Sources</b> can be seen as generalized iterators, allowing a given program to control answer production in another. Each Answer Source works as a separate Horn Clause LD-resolution interpreter.</p>
<p class="p9">The <b>Answer Source</b> constructor initializes a new interpreter.</p>
<p class="p14">answer_source(AnswerPattern,Goal,AnswerSource)</p>
<p class="p4">creates a new Horn Clause solver, uniquely identified by <b>AnswerSource</b> (a Source Fluent), which shares code with the currently running program and is initialized with resolvent <b>Goal</b>. <b>AnswerPattern</b> is a term, usually a list of variables occurring in <b>Goal</b>.</p>
<p class="p9">The <b>get/2</b> operation (provided by all <b>Sources</b>) is used to retrieve successive answers generated by an Answer Source, on demand.</p>
<p class="p14">get(AnswerSource,AnswerInstance)</p>
<p class="p4">tries to harvest the answer computed starting from <b>Goal</b>, as a instance of <b>AnswerPattern</b>. If an answer is found it is returned as <b>the(AnswerInstance)</b>, otherwise <b>no</b> is returned. Note that once <b>no</b> has been returned, all subsequent <b>get/2</b> on the same <b>AnswerSource</b> will return <b>no</b>. Bindings are not propagated to the original <b>Goal</b> or <b>AnswerPattern</b> when <b>get</b> retrieves an answer, i.e. <b>AnswerInstance</b> is obtained by first standardizing apart (renaming) the variables in <b>Goal</b> and <b>AnswerPattern</b>, and then backtracking over its alternative answers in a separate Prolog interpreter. Therefore, backtracking in the caller interpreter does not interfere with the new Answer Source's iteration over answers. Note however that backtracking over the Answer Source's creation point as such makes it unreachable and therefore subject to garbage collection.</p>
<p class="p9">Finally, an Answer Source is stopped with the <b>stop/1</b> operation implemented by all <b>Sources</b>.</p>
<p class="p14">stop(AnswerSource)</p>
<p class="p4">The <b>stop/1</b> operation is called automatically when no more answers can be produced as well as through the Fluent's <b>undo</b> operation on backtracking.</p>
<h3 style="margin: 0.0px 0.0px 14.0px 0.0px; font: 14.0px Times"><b> Source level extensions through new definitions</b></h3>
<p class="p4">To give a glimpse to the expressiveness of the resulting language, we will know introduce, through definitions in Kernel Prolog, a number of predicates known as `impossible to emulate' in Horn Clause Prolog (except by significantly lowering the level of abstraction and implementing something close to a Turing machine).</p>
<h4 style="margin: 0.0px 0.0px 15.0px 0.0px; font: 12.0px Times"><b>Negation and </b><span class="s3"><b>once/1</b></span></h4>
<p class="p4">These constructs are implemented simply by discarding all but the first solution produced by a Solver.<span class="Apple-converted-space"> </span></p>
<p class="p15">% returns the(X) or no as first solution of G<span class="s4"><span class="Apple-converted-space"> </span></span></p>
<p class="p15">first_solution(X,G,Answer):-<span class="s4"><span class="Apple-converted-space"> </span></span></p>
<p class="p15">  answer_source(X,G,Solver),<span class="s4"><span class="Apple-converted-space"> </span></span></p>
<p class="p15">  get(Solver,R),<span class="s4"><span class="Apple-converted-space"> </span></span></p>
<p class="p15">  stop(Solver),<span class="s4"><span class="Apple-converted-space"> </span></span></p>
<p class="p15">  eq(Answer,R).</p>
<p class="p16">% succeeds by binding G to its first solution or fails<span class="s4"> <br>
</span>once(G):-first_solution(G,G,the(G)).</p>
<p class="p16">% succeeds without binding G, if G fails<span class="s4"> <br>
</span>not(G):-first_solution(_,G,no).<span class="s4"> <br>
 </span></p>
<h4 style="margin: 0.0px 0.0px 15.0px 0.0px; font: 12.0px Times"><b>Reflective Meta-Interpreters</b></h4>
<p class="p4">The simplest meta-interpreter <b>metacall/1</b> just reflects backtracking through <b>element_of/2</b> over deterministic Answer Source operations.</p>
<p class="p14">metacall(Goal):-</p>
<p class="p14">  answer_source(Goal,Goal,E),</p>
<p class="p14">  element_of(E,Goal).</p>
<p class="p14">  </p>
<p class="p14">element_of(I,X):-get(I,the(A)),select_from(I,A,X).</p>
<p class="p17"><br></p>
<p class="p14">select_from(_,A,A).</p>
<p class="p14">select_from(I,_,X):-element_of(I,X).</p>
<p class="p4">We can see <b>metacall/1</b> as an operation which fuses two orthogonal language features provided by Answer Sources: <i>computing an answer of a Goal</i>, and <i>advancing to the next answer</i>, through the source level operations <b>element_of/2</b> and <b>select_from/3</b> which 'borrow' the ability to backtrack from the underlying interpreter.</p>
<p class="p9"><i>Note that </i><b><i>element_of/2</i></b><i> works generically on </i><b><i>Sources</i></b><i> and is therefore reusable, for instance, to backtrack over the character codes of a file or a URL</i>.</p>
<p class="p9">We can now build a meta-interpreter which implements the transitive closure of the unfolding operation (provided as the get/2 operation of an Unfolder Source in the underlying implementation language), combined with backtracking trough <b>element_of/2</b>.</p>
<p class="p14">unfold_solve(Goal):-</p>
<p class="p14">  unfold(':-'(Goal,Goal),':-'(Goal,true)).</p>
<p class="p17"><br></p>
<p class="p14">unfold(Clause,Clause).</p>
<p class="p14">unfold(Clause,Answer):-</p>
<p class="p14">  unfolder_source(Clause,Unfolder),</p>
<p class="p14">  element_of(Unfolder,NewClause),</p>
<p class="p14">  unfold(NewClause,Answer).</p>
<h4 style="margin: 0.0px 0.0px 15.0px 0.0px; font: 12.0px Times"><b>If-then-else</b></h4>
<p class="p4">Once we have first solution and metacall operations, emulating if-then-else is easy.</p>
<p class="p14">% if Cond succeeds executes Then otherwise Else</p>
<p class="p14">if(Cond,Then,Else):-</p>
<p class="p14">  first_solution(successful(Cond,Then),Cond,R),</p>
<p class="p14">  select_then_else(R,Cond,Then,Else).</p>
<p class="p17"><br></p>
<p class="p14">select_then_else(the(successful(Cond,Then)),Cond,Then,_):-Then.</p>
<p class="p14">select_then_else(no,_,_,Else):-Else.</p>
<h4 style="margin: 0.0px 0.0px 15.0px 0.0px; font: 12.0px Times"><b>All-solution predicates</b></h4>
<p class="p4">All-solution predicates like findall/3 can be obtained simply as:</p>
<p class="p16">findall(X,G,Xs):-<span class="s4"> <br>
</span>   answer_source(X,G,Solver),<span class="s4"> <br>
</span>   source_list(Solver,Xs).</p>
<p class="p9">We also provide a direct implementation of <b>Database Fluents</b>, which reflect to object level the interpreter's own handling of the Prolog database. As an additional benefit, multiple databases are provided. See predicates starting with <b>db_</b> for operations on databse fluents, in file lib.pro.</p>
<h3 style="margin: 0.0px 0.0px 14.0px 0.0px; font: 14.0px Times"><b>Lists and Terms as Source Fluents</b></h3>
<p class="p4">Sequential Prolog data structures are mapped to Fluents naturally. For instance, <b>list_source/2</b> creates a new Fluent based on a List, such that its <b>get/2</b> operation will return one element of the list at a time. Similarly <b>term_source/2</b> creates a Fluen from an N-argument compound term, such that its <b>get/2</b> method will return firs its function symbol then each argument. These built-ins are usable to emulate conventional Prolog operations like <b>univ/2</b> (also known as <span class="s3">=..</span>) quite easily:</p>
<p class="p14">univ(T,FXs):-if(var(T),list_to_fun(FXs,T),fun_to_list(T,FXs)).</p>
<p class="p17"><br></p>
<p class="p14">list_to_fun(FXs,T):-list_source(FXs,I),source_term(I,T).</p>
<p class="p14">fun_to_list(T,FXs):-term_source(T,I),source_list(I,FXs).</p>
<p class="p4">As they can be converted easily to/from Prolog data-structures, Fluents are usable as canonical representation for data objects as well as for computational processes (like in the case of <b>answer_sources</b>). Note that they also allow fast iteration using loops over efficient native data structures in the implementation language instead of recursion in the object language. Clearly, interfacing with external objects is also made simpler by this fact.<span class="Apple-converted-space"> </span></p>
<p class="p4"> </p>
<h3 style="margin: 0.0px 0.0px 14.0px 0.0px; font: 14.0px Times"><b>Arithmetics</b></h3>
<h4 style="margin: 0.0px 0.0px 15.0px 0.0px; font: 12.0px Times"><b>Arithmetics through built-in and user defined functions</b></h4>
<p class="p4">Note that one can assume, at an abstract level, that arithmetics is part of Kernel Prolog through the usual extension of Horn Clauses with successor arithmetics.</p>
<p class="p9">Kernel Prolog provides a unique built-in for handling arithmetic functions,</p>
<p class="p14">  compute(Operation,Arg1,Arg2,Result)</p>
<p class="p4">An enhanced <b>is/2</b> evaluator, supporting execution of arbitrary user defined functions of N arguments provided as N+1 argument Prolog relations, is implemented at source level.</p>
<h4 style="margin: 0.0px 0.0px 15.0px 0.0px; font: 12.0px Times"><b>Lazy Arithmetics with Fluents</b></h4>
<p class="p4">Arithmetic operations producing sequences like random number generators, primes, arithmetic or geometric series etc. can be implemented efficiently in the underlying language and provided in Kernel Prolog as fluents. Our reference implementation provides a generic</p>
<p class="p14">  integer_source(MaxFuel,A,X,B).</p>
<p class="p4">built-in operation allowing iterated computation of X&lt;-A*X+B at most MaxFuel times (or an infinite sequence if MaxFuel = 0). Building specialized arithmetic operations on top of this is quite easy:</p>
<p class="p18">% works with From =&lt; To as well as with To =&lt; From<span class="s4"> <br>
</span>counter(From,To,Counter):-<span class="s4"> <br>
</span>  compute('-',To,From,Dif),<span class="s4"> <br>
</span>  compute('?',To,From,Sign),<span class="s4"> <br>
</span>  compute('*',Dif,Sign,N),<span class="s4"> <br>
</span>  compute('+',N,1,Steps),<span class="s4"> <br>
</span>  integer_source(Steps,1,From,Sign,Counter).</p>
<p class="p18">for(I,From,To):-<span class="s4"> <br>
</span>  counter(From,To,Counter),<span class="s4"> <br>
</span>  element_of(Counter,I).</p>
<p class="p18">ints(From,To,Ns):-<span class="s4"> <br>
</span>  counter(From,To,Counter),<span class="s4"> <br>
</span>  source_list(Counter,Ns).</p>
<p class="p18">ints(Max,Ns):-ints(1,Max,Ns).<span class="s4"> <br>
 </span></p>
<h3 style="margin: 0.0px 0.0px 14.0px 0.0px; font: 14.0px Times"><b>Memoing Fluents</b></h3>
<p class="p4">Most Fluents are designed to be usable only once, by default, and release all resources held (automatically on backtracking or under programmer's control when their <b>stop</b> operation is invoked). While Fluent operations like <b>split_fluent/3</b> can be used to duplicate most Source Fluents, the following alternative provides a more efficient alternative.</p>
<p class="p9">A <b>Memoing Fluent</b> is built easily on top of a Source Fluent by accumulating values in a List or dynamic array. A Memoing Fluent can be shared between multiple consumers which want to avoid recomputation of a given value.</p>
<h4 style="margin: 0.0px 0.0px 15.0px 0.0px; font: 12.0px Times"><b>Fluent based Lazy Lists</b></h4>
<p class="p4">Lazy Lists can be seen as an instance of <b>Memoing Fluents</b>: they accumulate successive values of a Source Fluent in a (reusable) list. The simple Lazy List abstraction in our reference implementation works as follows:</p>
<p class="p14">  source_lazy_list(Source, LazyList)</p>
<p class="p4">creates a new LazyList object form a Source object:</p>
<p class="p14">  lazy_head(LazyList, LazyHead)</p>
<p class="p4">extracts the current head element of the list. Iteration over the list is provided by</p>
<p class="p14">  lazy_tail(LazyList, LazyTail)</p>
<p class="p4">which returns LazyTail, a new lazy list encapsulating the next stage of the Source fluent.</p>
<p class="p9">While complete automation of lazy lists through a form of attributed variable construct is possible, we have chosen a simpler implementation scenario based on the previously described operations, mainly because overriding unification with execution of an arbitrary procedure would introduce potential <i>non-termination</i> - something which would break the very idea of keeping the execution mechanism as close as possible to basic Horn Clause resolution, as available in classic Prolog.</p>
<p class="p9">Based on these operations, a lazy <b>findall/3</b> is simply:</p>
<p class="p14">% creates lazy list form an answer source</p>
<p class="p14">lazy_findall(X,G,LazyList):-</p>
<p class="p14">  answer_source(X,G,S),</p>
<p class="p14">  source_lazy_list(S,LazyList).</p>
<p class="p4">In fact, the behavior of the lazy list encapsulating <b>lazy_findall's</b> advancement on alternative solutions produced by an Answer Source, is indistinguishable from a lazy list constructed from an ordinary <b>list_source</b>:</p>
<p class="p14">% creates a lazy list from a lazy_list(List,LazyList):-</p>
<p class="p14">  list_source(List,S),</p>
<p class="p14">  source_lazy_list(S,LazyList).</p>
<p class="p4">The following operations will produce a lazily growing reusable list, to be explored with <b>lazy_element_of/2</b> in a way similar ordinary lists are explored with <b>member/2</b>.</p>
<p class="p14">% explores a lazy list in a way compatible with backtracking</p>
<p class="p14">% allows multiple 'consumers' to access the list, end ensures that</p>
<p class="p14">% the lazy list advances progressively and consistently</p>
<p class="p17"><br></p>
<p class="p14">lazy_element_of(XXs,X):-</p>
<p class="p14">  lazy_decons(XXs,A,Xs),</p>
<p class="p14">  lazy_select_from(Xs,A,X).</p>
<p class="p17"><br></p>
<p class="p14">% backtracks over the lazy list</p>
<p class="p14">lazy_select_from(_,A,A).</p>
<p class="p14">lazy_select_from(XXs,_,X):-lazy_element_of(XXs,X).</p>
<p class="p17"><br></p>
<p class="p14">% returns a head/tail pair of a non-empty lazy list</p>
<p class="p14">lazy_decons(XXs,X,Xs):-</p>
<p class="p14">  neq(XXs,[]),</p>
<p class="p14">  lazy_head(XXs,X),</p>
<p class="p14">  lazy_tail(XXs,Xs).</p>
<p class="p4">A minor change on Prolog's chronological backtracking is needed however: only the creation point of the lazy list is subject to trailing, and the complete lazy list is discarded at once. This is achieved easily in our reference implementation by giving to each lazy list its own (dynamically growing) trail, and by providing an <b>undo</b> operation which rewinds the trail completely when backtracking passes the lazy list object's creation point.</p>
<h3 style="margin: 0.0px 0.0px 14.0px 0.0px; font: 14.0px Times"><b>Multi Variables and Fluent based DCGs</b></h3>
<p class="p4">Multi-Variables are special Fluents which accumulate multiple values on an internal stack. As the stack is popped on backtracking multi-variables return to their previous values, therefore providing a form of backrackable destructive assignment. A new Multi-Variable is built with <b>def(MultiVar,InitialValue)</b>, it is uodated with <b>set(MultiVar,NewValue)</b> and its current value is retrived with <b>val(MultiVar,Value))</b>.</p>
<p class="p9">Among its applications, multi-stream DCGs, following BinPtrolog's Assumption Grammars implementation model, which does not require a DCG preprocessor, but uses backrackable destructive assignment instead, for advancing the state of a given DCG stream.</p>
<p class="p14">dcg_def(MultiVar,Xs):-def(MultiVar,Xs).</p>
<p class="p14">dcg_val(MultiVar,Xs):-val(MultiVar,Xs).</p>
<p class="p14">dcg_connect(MultiVar,X):-val(MultiVar,[X|Xs]),set(MultiVar,Xs).</p>
<p class="p4">The resulting implementation initializes an input list with <b>dcg_def/2</b>, retrieves its current value with <b>dcg_val/2</b> and advances with the <b>dcg_connect/2</b> relation, which consumes/generates a terminal symbol each time is called.</p>
<h3 style="margin: 0.0px 0.0px 14.0px 0.0px; font: 14.0px Times"><b><i>We refer to the file tarau/jinni/lib.pro for the precise semantics of Jinni built-ins and some other, less frequently used built-ins available in Jinni.</i></b></h3>
<h1 style="margin: 0.0px 0.0px 16.0px 0.0px; font: 24.0px Times"><b>Calling Kernel Prolog from Java</b></h1>
<p class="p9"><br>
A simple String to String function askJinni can be used to call Jinni from Java. Make sure you initialize Jinni first with something like <b>Init.run(null). </b>The string <b>s</b> returned by something like <b>String s=Init.askJinni("eq(X,1)"); </b>can be processed with Java String functions quite easily to extract the field containing the relevant answer. The following methods, from class Init.java, provide Term to Term functions for more efficient  Java to Jinni calls, not going through String representations.</p>
<p class="p9">  /** <br>
    Asks a quert\y to return Answer such tha Goal succeeds and returns the <br>
    first solution of the form "the(Answer)" or the constant  "no" if no solution exists <br>
  */ <br>
  public static Term askJinni(Term Answer,Term Goal) { <br>
    return Prog.fg(Answer,Goal); <br>
  }</p>
<p class="p9">  /** <br>
    Asks Jinni a query Goal and returns the <br>
    first solution of the form "the(Answer)" , where <br>
    Answer is an instance of Goal or the constant <br>
    "no" if no solution exists <br>
  */ <br>
  public static Term askJinni(Term Goal) { <br>
    return askJinni(Goal,Goal); <br>
  }</p>
<p class="p9">Look examples of their use  in some Java to Jinni calls in the GUI subdirectory, implementing Visual Jinni. <br>
 </p>
<h1 style="margin: 0.0px 0.0px 16.0px 0.0px; font: 24.0px Times"><b>Calling Java from Kernel Prolog</b></h1>
<p class="p4">Calling Java from Kernel Prolog happens through instances of FunBuiltin and ConstBuiltin. Each builtin has to be <i>registered</i>, allowing Kernel Prolog to<span class="Apple-converted-space"> </span></p>
<p class="p4">dynamically integrate it into its runtime system.</p>
<p class="p9">An example package in tarau/jinnigui is provided. Adding builtins is self explanatory once the programmer becomes aware of the following issues:</p>
<ul class="ul1">
  <li class="li4">The arity and Prolog name of the builtin is defined with <b>super(name,arity)</b> if &gt;0. In the case of arity 0, use instances of ConstBuiltin. There are no limits on arity.</li>
  <li class="li4">The arguments passed from  to Java are collected with <b>getArg(I),</b> with I in 0..arity-1, then casted to the appropriate</li>
  <li class="li4">Java types. Success is returned as 1, failure as 0, error as -1 in the <b>exec()</b>  method of the builtin.</li>
  <li class="li4">As many output arguments as needed are returned with <b>putArg(I) </b>which triggers unification on the Prolog side (for instance to bind a free variable to the returned value) possibly resulting in failure</li>
  <li class="li4"><b>getArg(I) </b>can also used to explore arguments of compound data, in particular lists</li>
  <li class="li4">Converting a list to a functor and back - with <b>univ/2</b> then accessing arguments one by one with getArg(I) is probably the best way to exchange lists with Jinni</li>
</ul>
<p class="p4"> </p>
</body>
</html>
